<?php

function ft($code=500,$message='fail',$data=''){
	if(empty($data)){
		$data = (object)array();
	}
	if($data == "0"){
		$data = $data;
	}
    return ['code'=>$code,'message'=>$message,'data'=>$data];	
}
/**
 * 返回信息
 * @param $message
 * @return array
 */
function ret_message($message = "") {
    if ($message == "") return ['code'=>200, 'message'=>''];
    $ret = lang($message);

    if (count($ret) != 2) {
        return ['code'=> 202,'message'=>'未知错误'];
    }
    return array(
        'code'  => $ret[0],
        'message' => $ret[1]
    );
}

/**
 * 发起http请求
 * @param string $url 访问路径
 * @param array $params 参数，该数组多于1个，表示为POST
 * @param int $expire 请求超时时间
 * @param array $extend 请求伪造包头参数
 * @param string $hostIp HOST的地址
 * @return array    返回的为一个请求状态，一个内容
 */
function makeRequest($url,$params)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据，json格式
}

/**
 * 读取/dev/urandom获取随机数
 * @param $len
 * @return mixed|string
 */
function randomFromDev($len,$result) {
    $result = md5($result);
    // convert from binary to string
    $result = base64_encode($result);
    // remove none url chars
    $result = strtr($result, '+/', '-_');

    return substr($result, 0, $len);
}

/**
 * [getUserId 获取用户id]
 * @param  [type] $openid [description]
 * @return [type]         [description]
 */
function getUserId($openid)
{
    $user = db('users')->where('wx_openid','eq',$openid)->where('status','eq',1)->find();
    return $user['id'];
}

/**
 * getDateName 获取名
 * @return [type]
 */
function getDateName(){
    $data = date('YmdHis',time());
	$data = $data.rand().rand().rand().rand();
    return $data;
}

/**
 * 定义邀请码生成算法
 * 10进制转36进制
 */
function codeChange($code)
{
    $a =  array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",

    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 

    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
    $rtn = '';
    while ($code >= 36) {
        $rtn = $a[fmod($code, 36)].$rtn;
        $code = floor($code/36);
    }
    return $a[$code].$rtn;
}

/**
 * 发红包
 * $total 红包总金额
 * $num 红包数目
 * $min 红包最小份额
 */
function randPacket($total,$num,$user_id,$packet_id,$min=0.01)
{    
    $data = array();
    for ($i=1;$i<$num;$i++)   
    {   
        $safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限   
        $money=mt_rand($min*100,$safe_total*100)/100;   
        $total=$total-$money;
        //插入数据库
        db('recieve_packet')->insert(array('user_id'=>$user_id,'packet_id'=>$packet_id,'fee'=>$money,'create_time'=>date('Y-m-d H:i:s',time())));
        // 返回数据  
        $data[$i]['money']   = $money;
        $data[$i]['surplus'] = $total;
    }
    return $data;
}


/**
 * 生成唯一订单号
 */
function OnlyOneOrderNumber()
{
    //订购日期

    $order_date = date('Y-m-d');

    //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）

    $order_id_main = date('YmdHis') . rand(10000000,99999999);

    //订单号码主体长度

    $order_id_len = strlen($order_id_main);

    $order_id_sum = 0;

    for($i=0; $i<$order_id_len; $i++){

    $order_id_sum += (int)(substr($order_id_main,$i,1));

    }

    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）

    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);

    return $order_id;
}

//二维数组排序
function arraySort($data,$key,$sorts='SORT_DESC')
{
    //重新排序
    $sort = array(  
            'direction' =>  $sorts, //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序  
            'field'     =>  $key,       //排序字段  
    );  
    $arrSort = array();  
    foreach($data AS $uniqid => $row){  
        foreach($row AS $key=>$value){  
            $arrSort[$key][$uniqid] = $value;  
        }  
    }  
    if($sort['direction']){ 
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data);  
    }   
    return $data;
}


//抽卡
function get_rand($proArr) {   
    $result = '';    
    //概率数组的总概率精度   
    $proSum = array_sum($proArr);    
    //概率数组循环   
    foreach ($proArr as $key => $proCur) {   
        $randNum = mt_rand(1, $proSum);   
        if ($randNum <= $proCur) {   
            $result = $key;   
            break;   
        } else {   
            $proSum -= $proCur;   
        }         
    }   
    unset ($proArr);    
    return $result;   
} 



function postCurl($url,$data,$type)  
{  
    if($type == 'json'){  
        $data = json_encode($data);//对数组进行json编码  
        $header= array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");  
    }  
    $curl = curl_init();  
    curl_setopt($curl,CURLOPT_URL,$url);  
    curl_setopt($curl,CURLOPT_POST,1);  
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);  
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);  
    if(!empty($data)){  
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);  
    }  
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);  
    curl_setopt($curl,CURLOPT_HTTPHEADER,$header);  
    $res = curl_exec($curl);  
    if(curl_errno($curl)){  
        echo 'Error+'.curl_error($curl);  
    }  
    curl_close($curl);  
    return $res;  
} 

function resetsame($data) {
    $num = count($data);
    $arr = array();
    foreach($data as $k => $v){
        if($v == null){
            unset($data[$k]);
        }
    }
    foreach($data as $k => $v){
        array_push($arr,$v);
    }
    $a = array();
    $count = count($arr);
    for($i=0;$i<$count-1;$i++){
        $k = $i + 1;
        if($arr[$i]->fid == $arr[$k]->fid){
            $score_a = $arr[$i]->inputval;
            $score_b = $arr[$k]->inputval;
            $arr[$i]->score = $score_a.':'.$score_b;
            array_push($a,$arr[$i]); 
            $i++;
        }
    }
    return $a;
}